#include "gudb.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <time.h>

static gudb* global_db = NULL;

void signal_handler(int sig) {
    if (sig == SIGINT || sig == SIGTERM) {
        printf("\nReceived signal %d, shutting down server...\n", sig);
        
        if (global_db) {
            gudb_server_stop(global_db);
            gudb_close(global_db);
            global_db = NULL;
        }
        
        exit(0);
    }
}

int main(int argc, char* argv[]) {
    printf("=== GuDB MySQL Server Test ===\n");
    
    // Parse command line arguments
    uint16_t port = 3316; // Default GuDB port
    char* data_dir = "/tmp/gudb_server_test";
    
    if (argc > 1) {
        port = (uint16_t)atoi(argv[1]);
    }
    if (argc > 2) {
        data_dir = argv[2];
    }
    
    printf("Starting GuDB server on port %u with data directory: %s\n", port, data_dir);
    
    // Set up signal handlers
    signal(SIGINT, signal_handler);
    signal(SIGTERM, signal_handler);
    
    // Create data directory
    char mkdir_cmd[512];
    snprintf(mkdir_cmd, sizeof(mkdir_cmd), "mkdir -p %s", data_dir);
    system(mkdir_cmd);
    
    // Initialize database
    printf("1. Initializing database...\n");
    global_db = gudb_open(data_dir, GU_OPEN_CREATE, "admin", "admin");
    if (!global_db) {
        printf("❌ Failed to initialize database\n");
        return 1;
    }
    printf("✅ Database initialized successfully\n");
    
    // Start network server
    printf("2. Starting network server...\n");
    int server_result = gudb_server_start(global_db, "0.0.0.0", port);
    if (server_result != GU_OK) {
        printf("❌ Failed to start network server: %d\n", server_result);
        gudb_close(global_db);
        return 1;
    }
    printf("✅ Network server started successfully\n");
    
    printf("\n🚀 GuDB MySQL Server is running!\n");
    printf("   - Port: %u\n", port);
    printf("   - Protocol: MySQL compatible\n");
    printf("   - Data directory: %s\n", data_dir);
    printf("   - To connect: mysql -h localhost -P %u -u admin -padmin\n", port);
    printf("   - Press Ctrl+C to stop the server\n\n");
    
    // Keep server running
    while (1) {
        sleep(1);
        
        // You could add server monitoring here
        // For example, print statistics every 60 seconds
        static int counter = 0;
        if (++counter >= 60) {
            counter = 0;
            printf("Server is running... (uptime: %llu seconds)\n", 
                   (unsigned long long)(time(NULL) - global_db->uptime_seconds));
        }
    }
    
    return 0;
}